package com.example.administrator.jingpingou.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.design.widget.FloatingActionButton;
import android.support.v4.app.Fragment;
import android.support.v4.view.PagerAdapter;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.EditText;
import android.widget.HorizontalScrollView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bartoszlipinski.recyclerviewheader.RecyclerViewHeader;
import com.example.administrator.jingpingou.R;
import com.example.administrator.jingpingou.adapter.ShopDataAdapter;
import com.example.administrator.jingpingou.adapter.ShopTitleAdapter;
import com.example.administrator.jingpingou.adapter.StageAdapter;
import com.example.administrator.jingpingou.application.MyApplication;
import com.example.administrator.jingpingou.bean.ShopTitleBean;
import com.example.administrator.jingpingou.bean.Shop_Data;
import com.example.administrator.jingpingou.bean.Shop_Two;
import com.example.administrator.jingpingou.config.NetConfig;
import com.example.administrator.jingpingou.netinteface.NetInterface;
import com.example.administrator.jingpingou.shop_activity.CameraActivity;
import com.example.administrator.jingpingou.shop_activity.ShopContentActivity;
import com.google.gson.Gson;
import com.jude.rollviewpager.RollPagerView;
import com.jude.rollviewpager.hintview.IconHintView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by Administrator on 2016/8/28 0028.
 */
public class ShopFragment extends Fragment {
//    @Bind(R.id.rvh_shop_main_head)
//    RecyclerViewHeader mHeaderView;
//
//    @Bind(R.id.rv_shop_main_show)
//    RecyclerView mRecylerData;


    private Retrofit mRetrofit;
    private NetInterface mNetInterface;
    private EditText mEditText;
    private ImageView mImgBottom;

    private RecyclerView mRecylerStage,mRecylerData;
    private GridLayoutManager mGridManager;
    private RecyclerView.Adapter mAdapter;
    private List<Shop_Data.ListYan> mData;

    private StaggeredGridLayoutManager mManager;
    private RecyclerView.Adapter mStageAdapter;
    private List<String> mDataTitle;
    private View view;
    private RecyclerViewHeader header;

    private List<ImageView> mImageView;
    private List<String> mImgData;
    private PagerAdapter mImgPagerAdapter;
//    private ViewHolder holder;
    private RollPagerView mViewPagerTitle,mViewPagerTwo;
    private HorizontalScrollView mScrollView;
    private RadioGroup mRadioGroupTop,mRadioGroupBottom;

    private FloatingActionButton mGoTopButton;
    private Intent intent;

    private int mPosition = 0;
    private List<String> mLink;

    private ImageView iv1,iv2;
    private TextView tv1Price,tv2Price,tv1Zhe,tv2Zhe;
    private LinearLayout llHead,llHeadOne,llHeadTwo;
    private MyApplication application;
    private List<Shop_Two.DataYan> shop_twoData;
    private String num_iid;
    private String num_iid1;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.shop_main,null);
        header = RecyclerViewHeader.fromXml(getActivity(),R.layout.shopmain_head);
        llHead = (LinearLayout) header.findViewById(R.id.ll_shop_head);
        initView(view);
        initHeadView(header);
        initData();
        setData();
        setListener();
        onClick();
        return view;
    }

    private void initHeader() {
        header.attachTo(mRecylerData);

        mViewPagerTitle.setPlayDelay(1500);

        mViewPagerTitle.setAdapter(mImgPagerAdapter);
        mViewPagerTitle.setHintView(new IconHintView(getActivity(),R.mipmap.xin,R.mipmap.shangxin));


    }

    private void onClick() {
        mGoTopButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(v!=null) {
                    mRecylerData.scrollToPosition(0);
//                    header = RecyclerViewHeader.fromXml(getActivity(),R.layout.shopmain_head);
//                    header.setVisibility(View.VISIBLE);
//                    initHeader();
                }
            }
        });
    }

    private void initHeadView(RecyclerViewHeader header) {
        mViewPagerTitle = (RollPagerView) header.findViewById(R.id.rpv_shopmain_head_one);
        mRadioGroupTop = (RadioGroup) header.findViewById(R.id.rg_main_head_top);
        mRadioGroupBottom = (RadioGroup) header.findViewById(R.id.rg_main_head_bottom);
        mScrollView = (HorizontalScrollView) header.findViewById(R.id.hs_shopmain_head_two);
        tv1Price = (TextView) header.findViewById(R.id.tv_shop_head_two_price1);
        tv2Price = (TextView) header.findViewById(R.id.tv_shop_head_two_price2);
        tv1Zhe = (TextView) header.findViewById(R.id.tv_shop_head_two_zhe1);
        tv2Zhe = (TextView) header.findViewById(R.id.tv_shop_head_two_zhe2);
        iv1 = (ImageView) header.findViewById(R.id.iv_shop_head_two_content1);
        iv2 = (ImageView) header.findViewById(R.id.iv_shop_head_two_content2);
        llHeadOne  = (LinearLayout) header.findViewById(R.id.ll_shop_head_one);
        llHeadTwo  = (LinearLayout) header.findViewById(R.id.ll_shop_head_two);
    }

    private void setData() {

        mRecylerStage.setLayoutManager(mManager);
        mRecylerStage.setAdapter(mStageAdapter);

        mRecylerData.setLayoutManager(mGridManager);
        mRecylerData.setAdapter(mAdapter);

        initHeader();
    }

    private void initData() {

        mImageView = new ArrayList<>();
        mImgData = new ArrayList<>();
        mLink = new ArrayList<>();
        x.http().get(new RequestParams(NetConfig.SHOP_MAIN_TITLE_PATH), new org.xutils.common.Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                Gson gson = new Gson();
                Log.d("TAG", "onSuccess: result=========="+result);
                ShopTitleBean shopTitleBean = gson.fromJson(result, ShopTitleBean.class);
                List<ShopTitleBean.DataYan> data = shopTitleBean.getData();
                for (int i = 0; i < data.size(); i++) {
                    ShopTitleBean.DataYan dataYan = data.get(i);
                    String ipadzimg = dataYan.getIpadzimg();
                    String link = dataYan.getLink();
                    mLink.add(link);
                    mImgData.add(ipadzimg);
                    ImageView imageView = new ImageView(getActivity());
                    x.image().bind(imageView,ipadzimg);
                    mImageView.add(imageView);
                    mImgPagerAdapter.notifyDataSetChanged();
                }
                Log.d("TAG", "onSuccess:mImgData =================="+mImgData+"\n"+mLink);
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

        mImgPagerAdapter = new ShopTitleAdapter(mImageView,getActivity(),mLink);

        mDataTitle = new ArrayList<>();
        x.http().get(new RequestParams(NetConfig.SHOP_MAIN_TOP_PATH), new org.xutils.common.Callback.CommonCallback<String>() {
            @Override
            public void onSuccess(String result) {
                try {
                    JSONArray arr = new JSONArray(result);
                    JSONObject jsonObject = arr.getJSONObject(0);
                    JSONArray list = jsonObject.getJSONArray("list");
                    for (int j = 0; j <list.length(); j++) {
                        JSONArray jsonArray = list.getJSONArray(j);
                        String string = jsonArray.getString(1);

                        mDataTitle.add(string);
                        mStageAdapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Throwable ex, boolean isOnCallback) {

            }

            @Override
            public void onCancelled(CancelledException cex) {

            }

            @Override
            public void onFinished() {

            }
        });

        mStageAdapter = new StageAdapter(mDataTitle,getActivity());
        mManager = new StaggeredGridLayoutManager(4,StaggeredGridLayoutManager.VERTICAL);

        mData = new ArrayList<>();
        mRetrofit = new Retrofit.Builder().baseUrl(NetConfig.SHOP_MAIN_DATA_PATH)
                .addConverterFactory(GsonConverterFactory.create()).build();
        mNetInterface = mRetrofit.create(NetInterface.class);
        Call<ResponseBody> shopMainData = mNetInterface.getShopMainData("0");
        shopMainData.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if(response.isSuccessful()) {
                    try {
                        String string = response.body().string();
                        Log.d("TAG", "onResponse: ========"+string);
                        application = (MyApplication) getActivity().getApplication();
                        String str = application.decodeUnicode(string);
//                        Log.d("TAG", "onResponse: ========"+str);
                        Gson gson = new Gson();
                        Shop_Data shop_data = gson.fromJson(str, Shop_Data.class);
                        List<Shop_Data.ListYan> list = shop_data.getList();
                        mData.addAll(list);

//                        Log.d("TAG", "onResponse: ========"+mData);
                        mAdapter.notifyDataSetChanged();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });


        mAdapter = new ShopDataAdapter(mData,getActivity());
        mGridManager = new GridLayoutManager(getActivity(),2, GridLayoutManager.VERTICAL,false);



        mRetrofit = new Retrofit.Builder().baseUrl(NetConfig.SHOP_DATA_TWO_PATH)
                .addConverterFactory(GsonConverterFactory.create()).build();
        mNetInterface = mRetrofit.create(NetInterface.class);
        Call<ResponseBody> xihuan = mNetInterface.getShopTwoData("xihuan");
        xihuan.enqueue(new Callback<ResponseBody>() {
            @Override
            public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                if(response.isSuccessful()) {
                    try {
                        String string = response.body().string();
                        Log.d("TAG", "onResponse: ========"+string);
                        application = (MyApplication) getActivity().getApplication();
                        String str = application.decodeUnicode(string);
//                        Log.d("TAG", "onResponse: ========"+str);
                        try {
                            JSONObject obj = new JSONObject(str);
                            JSONArray data = obj.getJSONArray("data");
//                    for (int i = 0; i < data.length(); i++) {
                            JSONObject jsonObject = data.getJSONObject(0);
                            num_iid = jsonObject.getString("num_iid");
                            String now_price = jsonObject.getString("now_price");
                            String discount = jsonObject.getString("discount");
                            String pic_url = jsonObject.getString("pic_url");
                            Log.d("TAG", "onSuccess: now_price============="+now_price+discount);
                            tv1Price.setText("¥"+now_price);
                            if("".equals(discount)) {
                                tv1Zhe.setText("?"+"折");
                            }else {
                                tv1Zhe.setText(discount+"折");
                            }
                            x.image().bind(iv1,pic_url);
//                    }
                            JSONObject jsonObject1 = data.getJSONObject(1);
                            num_iid1 = jsonObject1.getString("num_iid");
                            String now_price1 = jsonObject1.getString("now_price");
                            String discount1 = jsonObject1.getString("discount");
                            String pic_url1 = jsonObject1.getString("pic_url");

                            tv2Price.setText("¥"+now_price1);
                            if("".equals(discount1+"")) {
                                tv2Zhe.setText("?"+"折");
                            }else {
                                tv2Zhe.setText(discount1+"折");
                            }
                            x.image().bind(iv2,pic_url1);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }

                }
            }

            @Override
            public void onFailure(Call<ResponseBody> call, Throwable t) {

            }
        });


    }

    private void setListener() {
        final Animation animationIn = new TranslateAnimation(
          Animation.RELATIVE_TO_SELF,0,
                Animation.RELATIVE_TO_SELF,0,
                Animation.RELATIVE_TO_SELF,-1,
                Animation.RELATIVE_TO_SELF,0f
        );
        final Animation animationBack = new TranslateAnimation(
                Animation.RELATIVE_TO_SELF,0,
                Animation.RELATIVE_TO_SELF,0,
                Animation.RELATIVE_TO_SELF,0f,
                Animation.RELATIVE_TO_SELF,-1
        );
        mEditText.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mRecylerStage.setVisibility(View.VISIBLE);
                mRecylerStage.setAnimation(animationIn);
                animationIn.setDuration(1000);
                animationIn.setFillAfter(true);
                animationIn.start();
                mImgBottom.setVisibility(View.VISIBLE);
            }
        });
        mImgBottom.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                mRecylerStage.setVisibility(View.INVISIBLE);
                mRecylerStage.setAnimation(animationBack);
                animationBack.setDuration(1000);
                animationBack.setFillAfter(true);
                animationBack.start();
                mImgBottom.setVisibility(View.INVISIBLE);
            }
        });
//        mViewPager.setAdapter(mAdapter);


        mRadioGroupTop.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                intent = new Intent(getActivity(),CameraActivity.class);
                switch (checkedId) {
                    case R.id.rb_shop_head_camera :
                        intent.putExtra("title","数码");
                        intent.putExtra("path","1");
                        break;
                    case R.id.rb_shop_head_women :
                        intent.putExtra("title","女装");
                        intent.putExtra("path","2");
                        break;
                    case R.id.rb_shop_head_man :
                        intent.putExtra("title","男装");
                        intent.putExtra("path","3");
                        break;
                    case R.id.rb_shop_head_home :
                        intent.putExtra("title","家居");
                        intent.putExtra("path","4");
                        break;
                    case R.id.rb_shop_head_MAS :
                        intent.putExtra("title","母婴");
                        intent.putExtra("path","5");
                        break;
                }
                startActivity(intent);
            }
        });
        mRadioGroupBottom.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                intent = new Intent(getActivity(),CameraActivity.class);
                switch (checkedId) {
                    case R.id.rb_shop_head_shoes :
                        intent.putExtra("title","鞋包");
                        intent.putExtra("path","6");
                        break;
                    case R.id.rb_shop_head_dai :
                        intent.putExtra("title","配饰");
                        intent.putExtra("path","7");
                        break;
                    case R.id.rb_shop_head_beauty :
                        intent.putExtra("title","美妆");
                        intent.putExtra("path","8");
                        break;
                    case R.id.rb_shop_head_food :
                        intent.putExtra("title","美食");
                        intent.putExtra("path","9");
                        break;
                    case R.id.rb_shop_head_other :
                        intent.putExtra("title","其他");
                        intent.putExtra("path","10");
                        break;
                }
                startActivity(intent);
            }
        });

        llHeadOne.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(),ShopContentActivity.class);
                intent.putExtra("path",num_iid);
                startActivity(intent);
            }
        });
        llHeadTwo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(),ShopContentActivity.class);
                intent.putExtra("path",num_iid1);
                startActivity(intent);
            }
        });
    }

    private void initView(View view) {
        mRecylerData = (RecyclerView) view.findViewById(R.id.rv_shop_main_show);
        mEditText = (EditText) view.findViewById(R.id.et_shop_main_sousuo);
        mRecylerStage = (RecyclerView) view.findViewById(R.id.rv_shop_main_sousuo);
        mImgBottom = (ImageView) view.findViewById(R.id.iv_shop_main_bottom);
        mGoTopButton = (FloatingActionButton) view.findViewById(R.id.fb_shop_first);
    }
}
